package znck.spring.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * BaseDao
 * @author wxj233
 * @version 1.0
 * @param <T>
 */
@SuppressWarnings("all")
public class BaseDao<T> {

	@Autowired
	private SessionFactory sessionFactory;
	
	private Class entityclass;
	public BaseDao() {
		Type type = this.getClass().getGenericSuperclass();
		Type[] types = ((ParameterizedType)type).getActualTypeArguments();
		entityclass = (Class) types[0];
	}
	
	public T get(Serializable id) {  //Integer是实现了Serializable接口的
		return (T) sessionFactory.getCurrentSession().get(entityclass, id);
	}
	
	public T load(Serializable id) {
		return (T) sessionFactory.getCurrentSession().load(entityclass, id);
	}
	
	public void save(T entity) {
		 sessionFactory.getCurrentSession().save(entity);
	}
	
	public void update(T entity) {
		sessionFactory.getCurrentSession().update(entity);
	}
	
	public void update( String hql) {
		getlocalSession().createQuery(hql).executeUpdate();
	}
	
	public void delete(T entity) {
		sessionFactory.getCurrentSession().delete(entity);
	}
	
	public void delete( String hql) {
		getlocalSession().createQuery(hql).executeUpdate();
	}
	
	public List<T> query(String hql){
		return (List<T>)sessionFactory.getCurrentSession().createQuery(hql).getResultList();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 获取当前线程session
	 * @return Session
	 */
	public Session getlocalSession() {
		return sessionFactory.getCurrentSession();
	}	
	
	/**
	 * 将脱管状态的对象变为持久化状态,从新向数据库发送一条sql，查询该实体化类并更新该实体化类，同时持久化该类
	 */
	public void updateObj(T entity) {
		getlocalSession().refresh(entity);
	}
	
	/**
	 * 分页查询
	 */
	
}
